package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.json.JSONUtil;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.ResponseData;
import com.rzjm.api.netty.water.constant.ResultCodeEnum;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterOrderService;
import com.rzjm.api.service.IDeviceWaterService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 *  刷卡后的出水  绿色按钮 请求
 * @author Mr.Zhou
 * @Description:
 * @date 2025/3/17 9:27
 */
@Component
public class Receive12InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive12InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;
    @Autowired
    private IDeviceWaterOrderService waterOrderService;


    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        //保存Channel
        NettyUtil.addChannel(ctx, receiveData.getId());
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
                .ifPresent(message -> deviceMessagesService.save(message));

        //设备应答消息
        String tag = receiveData.getV2() != null ? receiveData.getV2() : receiveData.getTag()+"";
        if (tag != null && NettyUtil.SYNC_RESPONSEDATA_MAP.containsKey(tag)) {
            ResponseData responseData = NettyUtil.SYNC_RESPONSEDATA_MAP.get(tag);
            if (responseData != null) {
                String message = JSONUtil.toJsonStr(receiveData);
                responseData.setCode(ResultCodeEnum.OK.getCode());
                responseData.setMsg(ResultCodeEnum.OK.getDescription());
                responseData.setReceiveDataStr(message);
                responseData.setReceiveData(receiveData);
                responseData.getPromise().setSuccess();
            }
        } else {
            //同步消息或同步非阻塞消息，暂时没有处理逻辑
        }
    }

}
